package cn.jiedh.app.meiweidk.survey;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AutoSizeImageView;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LoadUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.TimeUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.SurveyBean;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;


/**
 * @name：MXK
 * @author：达摩
 * @phone：
 * @createTime： 十月-23
 * @modifyTime： 21:16:10
 * @explain：调研页面
 */
public class SurveyActivity extends BaseActivity {

    public static final int SUVEYRESULT = 333;

    @BindView(R.id.bar_tv_title)
    TextView title;
    @BindView(R.id.survey_icon)
    AutoSizeImageView survey_icon;
    @BindView(R.id.survey_name)
    TextView survey_name;
    @BindView(R.id.survey_loan)
    TextView survey_loan;//可贷额度(元)
    @BindView(R.id.survey_type)
    TextView survey_type;//利率类型 1月利率 2日利率
    @BindView(R.id.survey_rate)
    TextView survey_rate;//参考日利率
    @BindView(R.id.survey_tips)
    TextView survey_tips;//提示

    @BindView(R.id.survey_problem)
    LinearLayout survey_problem;
    @BindView(R.id.survey_ok)
    Button survey_ok;
    FullyLinearLayoutManager mLayoutManager;

    int productId;//产品ID
    SurveyBean surveyBean;
    private List<BuriedBean> buriedList;
    private long pageEnterTime;

    private boolean isApply = false;//是否提交了调查问卷

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_survey;
    }

    @Override
    protected void initView(View view) {
        Date date = new Date(System.currentTimeMillis());
        pageEnterTime = date.getTime();
        title.setText(getResources().getString(R.string.survey_title));
        setBack(true);
        mLayoutManager = new FullyLinearLayoutManager(this);
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            productId = bundle.getInt("productId");
            surveyBean = (SurveyBean) bundle.getSerializable("surveyBean");
        }
        if (productId != 0) {

        }
        if (surveyBean != null) {
            refresh(surveyBean);
        }
    }

    /**
     * 提交问卷
     */
    void sendData() {
        Map map = new HashMap<String, Objects>();
        buriedList = new ArrayList<>();
        buriedList.add(new BuriedBean("question", "进行了调查问卷", "8", "", "已提交", "调查问卷", "false", "", "", "", "", "", "", "", "", "", ""));
        SPUtils.saveBuriedList(buriedList);
        map.put("productId", surveyBean.getProductId());//	是	int	产品ID
        map.put("productName", surveyBean.getProductName());// 是String	产品名
        map.put("questionnaireId", surveyBean.getQuestionnaireId());//	是	int	问卷ID
        map.put("questionnaireName", surveyBean.getQuestionnaireName());// 是	int	问卷名
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < surveyBean.getProblemList().size(); i++) {
            if (TextUtils.isEmpty(surveyBean.getProblemList().get(i).getAnswer())) {
                T.showShortToast(getResources().getString(R.string.survey_unfinish));
                return;
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("problemId", surveyBean.getProblemList().get(i).getProblemId());//	是	int	回答的问题的ID
                jsonObject.put("answer", surveyBean.getProblemList().get(i).getAnswer());//	是	String	用户回答 多条选项以&隔开
                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        map.put("answerList", jsonArray);//	是	String	回答列表

        request(this, UrlUtils.SURVEYSEND, map, false, new ResponseSuccess() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                if (response.getCode() == 0) {
                    T.showShortToast(getResources().getString(R.string.survey_success));
                    finish();
                } else {
                    T.showShortToast(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化banner错误" + msg);
                T.showShortToast(msg);
            }
        });
    }

    /**
     * 刷新页面
     *
     * @param surveyBean
     */
    void refresh(SurveyBean surveyBean) {
        if (surveyBean != null) {

            LoadUtils.loadImage(this,surveyBean.getProductImgUrl(),survey_icon);

//            Glide.with(this).load(surveyBean.getProductImgUrl()).placeholder(R.drawable.green_loading).error(R.drawable.load_fail).into(survey_icon);
            survey_name.setText(surveyBean.getProductName());
            survey_tips.setText(Html.fromHtml(String.format(getString(R.string.survey_tips), surveyBean.getProductName())));
            String moneyMin = new Double(surveyBean.getMoneyMin()).intValue() + "";
            String moneyMax = new Double(surveyBean.getMoneyMax()).intValue() + "";
            if (moneyMin.length() >= 6) {
                moneyMin = new Double(surveyBean.getMoneyMin()).intValue() / 10000 + "";
            } else {
                moneyMin = new Double(surveyBean.getMoneyMin()).intValue() + "";
            }
            if (moneyMax.length() >= 6) {
                moneyMax = new Double(surveyBean.getMoneyMax()).intValue() / 10000 + "万";
            } else {
                moneyMax = new Double(surveyBean.getMoneyMax()).intValue() + "";
            }
            survey_loan.setText(moneyMin + "-" + moneyMax);
            survey_rate.setText(surveyBean.getRate() + "%");
            if (surveyBean.getRateType() == 1) {//利率类型 1月利率 2日利率
                survey_type.setText("参考月利率");
            } else {
                survey_type.setText("参考日利率");
            }
            for (int i = 0; i < surveyBean.getProblemList().size(); i++) {
                SurveyBean.SurveyQuestion question = surveyBean.getProblemList().get(i);
                question.setProblem((i+1) + "、" + question.getProblem());
                int type = question.getType();
                switch (type) {// 1单选 2多选 3 文本
                    case 1:
                        addSingleChoose(question);
                        break;
                    case 2:
                        addMultiChoose(question);
                        break;
                    case 3:
                        addInutView(question);
                        break;
                }
            }
        }
    }

    @OnClick({R.id.survey_ok, R.id.bar_img_back})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.survey_ok:
                if (surveyBean.getProblemList().size() > 0) {
                    isApply = true;
                    sendData();
                }
                break;
            case R.id.bar_img_back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void finish() {
        if (!isApply) {
            buriedList = new ArrayList<>();
            buriedList.add(new BuriedBean("question", "没有进行调查问卷", "8", "", "没有提交", "调查问卷", "false", "", "", "", "", "", "", "", "", "", ""));
            SPUtils.saveBuriedList(buriedList);
        }
        Intent intent = new Intent();
        intent.putExtra("stayTime", TimeUtils.calculationRemainTime(pageEnterTime, 3));
        setResult(SUVEYRESULT, intent);
        super.finish();
    }

    /**
     * 增加单选
     */
    void addSingleChoose(SurveyBean.SurveyQuestion question) {
        TextView textView = getNewText();
        textView.setText(question.getProblem());
        String[] strings = getStringArray(question);

        LinearLayout.LayoutParams textLayoutPara = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textLayoutPara.setMargins(5, 10, 5, 10);
        textView.setLayoutParams(textLayoutPara);
        survey_problem.addView(textView);
        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.survey_radio_single, null);
        RadioGroup radioGroup = (RadioGroup) linearLayout.getChildAt(0);
        for (int i = 0; i < strings.length; i++) {
            RadioButton radioButton = new RadioButton(this);
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(10, 10, 10, 10);
            radioButton.setGravity(Gravity.LEFT);
            radioButton.setGravity(Gravity.CENTER_VERTICAL);
            radioButton.setLayoutParams(layoutParams);
            radioButton.setTextSize(14);
            radioButton.setPadding(10, 10, 10, 10);
            radioButton.setText(strings[i]);
            radioButton.setButtonDrawable(getResources().getDrawable(R.drawable.selector_radio));
            radioGroup.addView(radioButton);
            radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        question.setAnswer(compoundButton.getText().toString());
                    }
                }
            });
            View view = new View(this);
            RadioGroup.LayoutParams layoutParams1 = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
            layoutParams1.setMargins(0, 5, 0, 5);
            view.setLayoutParams(layoutParams1);
            view.setBackgroundColor(getResources().getColor(R.color.light_gray));
            radioGroup.addView(view);
        }
        survey_problem.addView(linearLayout);
    }

    /**
     * 增加多选
     */
    private void addMultiChoose(SurveyBean.SurveyQuestion question) {
        TextView textView = getNewText();
        textView.setText(question.getProblem());
        String[] strings = getStringArray(question);

        LinearLayout.LayoutParams textLayoutPara = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textLayoutPara.setMargins(5, 10, 5, 10);
        textView.setLayoutParams(textLayoutPara);
        survey_problem.addView(textView);
        for (int i = 0; i < strings.length; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.survey_radio_multi, null);
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(10, 10, 10, 10);
            checkBox.setLayoutParams(layoutParams);
            checkBox.setGravity(Gravity.LEFT);
            checkBox.setGravity(Gravity.CENTER_VERTICAL);
            checkBox.setTextSize(14);
            checkBox.setPadding(10, 10, 10, 10);
            checkBox.setText(strings[i]);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        if (TextUtils.isEmpty(question.getAnswer())) {
                            question.setAnswer(compoundButton.getText().toString());
                        } else {
                            question.setAnswer(question.getAnswer() + "&" + compoundButton.getText().toString());
                        }
                    } else {
                        if (question.getAnswer().contains("&" + compoundButton.getText().toString())) {
                            question.setAnswer(question.getAnswer().replace("&" + compoundButton.getText().toString(), ""));
                        } else {
                            question.setAnswer(question.getAnswer().replace(compoundButton.getText().toString(), ""));
                        }
                    }
                }
            });
            survey_problem.addView(view);
        }
    }

    private String[] getStringArray(SurveyBean.SurveyQuestion question) {
        JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(question.getOption());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String[] strings = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                strings[i] = (String) jsonArray.get(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return strings;
    }

    /**
     * 增加文本框
     */
    void addInutView(SurveyBean.SurveyQuestion question) {
        TextView textView = getNewText();
        textView.setText(question.getProblem());
        EditText editText = new EditText(this);
        editText.setTextSize(14);
        editText.setMinLines(3);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(140)});
        survey_problem.addView(textView);
        survey_problem.addView(editText);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (editText.getText().toString().length() >= 140) {
                    T.showShort("最长输入140个字");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                question.setAnswer(editText.getText().toString());
            }
        });
    }

    TextView getNewText() {
        TextView textView = new TextView(this);
        textView.setTextColor(getResources().getColor(R.color.common_dark));
        textView.setTextSize(14);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        return textView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
